const net = require('net')

class Request {
  constructor (options) {
    this.method = options.method || 'GET',
    this.host = options.host
    this.port = options.port || 80
    this.path = options.path || '/'
    this.headers = options.headers || {}
    this.body = options.body || {}
    // 一定要有Content-Type请求头，且具有默认值，否则body无法解析
    if (!this.headers['Content-Type']) {
      this.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    }
    // 不同的Content-Type影响最后body的格式
    if (this.headers['Content-Type'] === 'application/json') {
      this.bodyText = JSON.stringify(this.body)
    } else if (this.headers['Content-Type'] === 'application/x-www-form-urlencoded') {
      this.bodyText = Object.keys(this.body).map(key => `${key}=${encodeURIComponent(this.body[key])}`).join('&')
    }

    this.headers['Content-Length'] = this.bodyText.length

  }

  send (connection) {
    return new Promise((res, rej) => {
      let parser = new ResponseParser()

      if (connection) {
        connection.write(this.toString())
      } else {
        connection = net.createConnection({
          host: this.host,
          port: this.port
        }, () => {
          console.log('request:',this.toString())
          connection.write(this.toString())
        })
      }

      connection.on('data', data => {
        console.log('data:', data.toString())
        parser.receive(data.toString())
        if (parser.isFinished) {
          res(parser.response)
          connection.end()
        }
      })

      connection.on('error', error => {
        rej(error)
        connection.end()
      })
      res()
    })
  }

  // 拼接request请求结构
  toString () {
    return `${this.method} ${this.path} HTTP/1.1\r
${Object.keys(this.headers).map(key => `${key}: ${this.headers[key]}`).join('\r\n')}\r
\r
${this.bodyText}`
  }
}


class ResponseParser {
  constructor () {}

  receive () {}
}

void async function () {

  const request = new Request({
    method: 'GET',
    port: 8080,
    host: '127.0.0.1',
    path: '/',
    headers: {
  
    },
    body: {
      name: 'pb'
    }
  })
  
  let response = await request.send()
}()